/*
 * Created by Huang 嵘才 on 18-7-23 下午2:48
 * Copyright (c) 2018. All rights reserved.
 * Last modified 18-7-23 下午2:48
 */

package com.esir.android;

import android.app.Activity;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

/**
 * 屏自适应配置
 * 请调用setDefault(Application)
 */

public class Density {
    static final String WIDTH = "width";
    static final String HEIGHT = "height";
    private static float appDensity;
    private static float appScaledDensity;
    private static DisplayMetrics appDisplayMetrics;
    private static float widthInDp = 360;
    private static float heightInDp = 640;

    private static float originalDensity;
    private static float originalScaledDensity;

    /**
     * app的onCreate里调用
     * 适配屏720*1280
     *
     * @param context {@linkplain Context}
     */
    public static void setDefault(final Context context) {
        init(context, 360, 640);
    }

    /**
     * app的onCreate里调用
     *
     * @param context  {@linkplain Context}
     * @param widthDp  ui给的设计图的宽度,单位是dp
     * @param heightDp ui 给的设计图的高度 单位dp
     */
    public static void init(final Context context, float widthDp, float heightDp) {
        widthInDp = widthDp;
        heightInDp = heightDp;
        //获取application的DisplayMetrics
        appDisplayMetrics = context.getResources().getDisplayMetrics();

        if (appDensity == 0) {
            //初始化的时候赋值
            appDensity = appDisplayMetrics.density;
            appScaledDensity = appDisplayMetrics.scaledDensity;

            originalDensity = appDisplayMetrics.density;
            originalScaledDensity = appDisplayMetrics.scaledDensity;

            //添加字体变化的监听
            context.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    //字体改变后,将appScaledDensity重新赋值
                    if (newConfig != null && newConfig.fontScale > 0) {
                        appScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {
                }
            });
        }
    }

    /**
     * 在activity的onCreate中,setContentView之前调用,按宽度适配
     *
     * @param activity {@linkplain Activity}
     */
    public static void adaptByWidth(Activity activity) {
        setAppOrientation(activity, WIDTH);
    }

    /**
     * * 在activity的onCreate中,setContentView之前调用,按高度适配
     *
     * @param activity {@linkplain Activity}
     */
    public static void adaptByHeight(Activity activity) {
        setAppOrientation(activity, HEIGHT);
    }

    /**
     * targetDensity
     * targetScaledDensity
     * targetDensityDpi
     * 这三个参数是统一修改过后的值
     * <p>
     * orientation:方向值,传入width或height  Density.WIDTH或者Density.HEIGHT
     */
    private static void setAppOrientation(Activity activity, String orientation) {

        float targetDensity = 0;
        try {
            double division;
            //根据带入参数选择不同的适配方向
            if (orientation.equals(HEIGHT)) {
                division = division(appDisplayMetrics.heightPixels, heightInDp);
            } else {
                division = division(appDisplayMetrics.widthPixels, widthInDp);
            }
            targetDensity = (float) Math.round(division * 100) / 100;
        } catch (Exception e) {
            e.printStackTrace();
        }

        float targetScaledDensity = targetDensity * (appScaledDensity / appDensity);
        int targetDensityDpi = (int) (160 * targetDensity);

        /*
         * 最后在这里将修改过后的值赋给系统参数
         * 只修改Activity的density值,不影响其他页面
         */

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;
    }

    private static double division(double a, double b) {
        double div = 0;
        if (b != 0) {
            div = a / b;
        } else {
            div = 0;
        }
        return div;
    }

    /**
     * 获取屏幕宽 （Pixels）
     *
     * @param context Context
     * @return 屏幕宽
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高 （Pixels）
     *
     * @param context Context
     * @return 屏幕高
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 获取屏幕宽高 （Pixels）
     *
     * @param context Context
     * @return 屏幕宽高；[0]=宽，[1]=高
     */
    public static int[] getScreenWH(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return new int[]{dm.widthPixels, dm.heightPixels};
    }
}
